package com.idbk.chargestation.activity.assist;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.MainActivity;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.app.ManagerADs;
import com.idbk.chargestation.bean.JsonADsWelcome;
import com.idbk.chargestation.bean.JsonLogin;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.GsonUtils;
import com.squareup.picasso.Picasso;


/**
 * 欢迎界面
 *
 * @author lupc, zhx
 */
public class ActivityWelcome extends Activity implements OnClickListener {

    public final static String TAG = ActivityWelcome.class.getSimpleName();
    public static final String FIRST_TO_LOGIN = "first_to_login";
    private ImageView mImageView;
    private TextView mTextTime;
    private boolean mAutoJumpToMain = true;
    private boolean isShowGuidePage = false;
    private int mTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_welcome);

        initView();

        initData();
    }

    private void initView() {
        mTextTime = (TextView) findViewById(R.id.textview_welcome_time);
        mImageView = (ImageView) findViewById(R.id.imageiew_welcome);
    }

    private void initData() {
        checkGuidePage();
        showPage();
        autoLogin();
    }

    private void checkGuidePage() {
        if (CheckUtil.isShowGuidePage()) {
            isShowGuidePage = true;
        }
    }

    private void showPage() {
        if (isShowGuidePage) {
            showWelcomeAndGuidePage();
        } else {
            showWelcomeOrAdvertisementPage();
        }
    }

    private void showWelcomeAndGuidePage() {
        // 显示欢迎界面1000毫秒后跳转至引导页
        mTextTime.setVisibility(View.GONE);
        mImageView.setImageResource(R.drawable.welcome);
        mImageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(ActivityWelcome.this, ActivityGuidePage.class);
                startActivity(intent);
                finish();
            }
        }, 800);
    }

    private void showWelcomeOrAdvertisementPage() {
        //读取广告信息，如果要显示广告，则显示广告
        ManagerADs manager = new ManagerADs(getApplicationContext());
        JsonADsWelcome data = manager.getWelcomeADInfo();
        if (data.isShow) {
            showAdvertisementPage(manager, data);
        } else {
            showWelcomePage();
        }
    }

    private void showWelcomePage() {
        mTime = 2000;
        mTextTime.setVisibility(View.GONE);
        mImageView.setImageResource(R.drawable.welcome);
        startDelayCountDown(0);
    }

    private void showAdvertisementPage(ManagerADs manager, final JsonADsWelcome data) {
        mTime = 3000;
        setLastTimeText(mTime / 1000);
        mTextTime.setOnClickListener(this);
        Picasso.with(this)
                .load(manager.getWelcomeADImage())
                .error(R.drawable.welcome)
                .placeholder(R.drawable.welcome)
                .into(mImageView);
        mImageView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mAutoJumpToMain = false;
                goToBrowser(data.linkURL);
            }
        });
        startDelayCountDown(0);
    }

    private void goToBrowser(String url) {
        Intent intent = new Intent(ActivityWelcome.this, ActivityBrowser.class);
        intent.putExtra(ActivityBrowser.KEY_URL, url);
        intent.putExtra(ActivityBrowser.KEY_IS_TO_MAIN, true);
        startActivity(intent);
        ActivityWelcome.this.finish();
    }

    private void setLastTimeText(int time) {
        String lastTime = time + "s|跳过";
        mTextTime.setText(lastTime);
    }

    private void startDelayCountDown(int delay) {
        mImageView.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (!mAutoJumpToMain) {
                    return;
                }
                mTime -= 1000;
                setLastTimeText(mTime / 1000);
                if (mTime <= 0) {
                    jumpToMainActivity();
                } else {
                    startDelayCountDown(1000);
                }
            }
        }, delay);
    }

    private void autoLogin() {
        AppContext ac = AppContext.getInstance();
        String username = ac.getLoginUserName();
        String password = ac.getLoginPassword();
        //如果登录时间太长，则重新登录
        if (ac.isLoginExpired()) {
            if (username != null && password != null) {
                ChargeStationAPI.login(username, password, ac.getPushClientId(),ac.getUserRole(), mResponse);
            }
        }
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonLogin result = GsonUtils.toBean(JsonLogin.class, response);
            if (result == null) {
                return;
            }
            if (result.status == 0) {
                //记录登录信息
                AppContext ac = AppContext.getInstance();
                AppContext.getInstance().saveUserInfo(
                        result.token,
                        ac.getLoginUserName(),
                        ac.getLoginPassword(),
                        result.outTime,
                        result.userRole);
            }
        }

    };

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.textview_welcome_time) {
            jumpToMainActivity();
            finish();
        }
    }

    private void jumpToMainActivity() {
        mAutoJumpToMain = false;
        Intent intent = new Intent(ActivityWelcome.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

}
